package com.xbongbong.pro.statistic.service.result;

import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OtherIncomeSheetTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.service.toolbox.statistic.util.ChartResultUtil;
import com.xbongbong.pro.statistic.constant.ChartI18Constant;
import com.xbongbong.pro.statistic.enums.NumFormatEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.enums.ValueTypeEnum;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.pro.statistic.result.pojo.MomYoyTimeListPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.StatisticResultDTO;
import com.xbongbong.pro.statistic.result.pojo.dto.StatisticResultInfoDTO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: 汪腾伟
 * @Description：其他收入结果分析
 * @Date: Created in 2021/6/4 10:20
 */
@Service
public class CrmOtherIncomeResult extends ChartResultParentService implements ChartResultSystem {

    @Override
    public Object getTarget(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        SystemCodeEnum systemCodeEnum = chartResultPojo.getSystemCodeEnum();
        switch (systemCodeEnum) {
            case OTHER_INCOME_AMOUNT_CHART:
                return otherIncomeAmountChart(chartResultPojo, chartResultDetailVO);
            case OTHER_INCOME_RED_AMOUNT_CHART:
                return otherIncomeRedAmountChart(chartResultPojo, chartResultDetailVO);
            default:
                break;
        }
        return null;
    }


    /**
     * 红冲收款退款金额分析
     *
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return
     */
    private Object otherIncomeRedAmountChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        List<String> legendList = Arrays.asList(I18nMessageUtil.getMessage(ChartI18Constant.OTHER_INCOME_RED_AMOUNT_CHART_TITLE).split(","));
        String unit = systemChartHelp.getUnit(I18nMessageUtil.getMessage(CommonConstant.YUAN));
        String unit1 = systemChartHelp.getUnit("%");
        List<String> unitList = Arrays.asList(unit, unit, unit, unit1, unit1);
        //红冲：红冲
        List<String> redCodeList = OtherIncomeSheetTypeEnum.getRedCodeList();
        StatisticResultDTO statisticResultDto = getStatisticOtherIncomeAmount(chartResultPojo, legendList, unitList, redCodeList);

        //右侧展示总数
        statisticResultDto.setTotalFlag(true);
        statisticResultDto.setValueTitle(I18nMessageUtil.getMessage(ChartI18Constant.TOTAL_AMOUNT_RED_PAYMENT_AMOUNT));
        chartResultDetailVO = systemChartHelp.packageResult(statisticResultDto, chartResultPojo, chartResultDetailVO);
        return chartResultDetailVO;
    }

    /**
     * 图表中心其他收入分析
     *
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return
     */
    private Object otherIncomeAmountChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        List<String> legendList = Arrays.asList(I18nMessageUtil.getMessage(ChartI18Constant.OTHER_INCOME_AMOUNT_CHART_TITLE).split(","));
        String unit = systemChartHelp.getUnit(I18nMessageUtil.getMessage(CommonConstant.YUAN));
        String unit1 = systemChartHelp.getUnit("%");
        List<String> unitList = Arrays.asList(unit, unit, unit, unit1, unit1);
        //已收款，不限制红冲
        List<String> allCodeList = OtherIncomeSheetTypeEnum.getAllCodeList();
        StatisticResultDTO statisticResultDto = getStatisticOtherIncomeAmount(chartResultPojo, legendList, unitList, allCodeList);

        //右侧展示总数
        statisticResultDto.setTotalFlag(true);
        statisticResultDto.setValueTitle(I18nMessageUtil.getMessage(ChartI18Constant.TOTAL_OTHER_INCOME_AMOUNT));
        chartResultDetailVO = systemChartHelp.packageResult(statisticResultDto, chartResultPojo, chartResultDetailVO);
        return chartResultDetailVO;
    }

    /**
     * 封装环比和同比金额
     *
     * @param chartResultPojo
     * @param legendList
     * @param unitList
     * @param typeList
     * @return
     */
    private StatisticResultDTO getStatisticOtherIncomeAmount(ChartResultPojo chartResultPojo, List<String> legendList, List<String> unitList, List<String> typeList) throws XbbException {
        chartResultPojo.setValueTypeEnum(ValueTypeEnum.VALUE_MONEY);
        //先把chartResultPojo拷贝出一份，下面都用chartResultPojoCopy，防止时间的变更对原有chartResultPojo内参数的影响
        Integer startTime = chartResultPojo.getStartTime();
        Integer endTime = chartResultPojo.getEndTime();
        //环比，上月开始--截止，startTime的前一个月，作为环比的开始时间；endTime的前一个月，作为环比的截止时间
        Integer lastMonthStartTime = DateUtil.getFirstDateOfLastMonth(startTime);
        Integer lastMonthEndTime = DateUtil.getFirstDateOfLastMonth(endTime);
        //同比，上年同期（上年同一个月）开始--截止：startTime的上年同月，作为同比的开始时间；endTime的上年同月第一天，作为同比的截止时间
        Integer lastYearStartTime = DateUtil.getFirstDateOfLastYear(startTime);
        Integer lastYearEndTime = DateUtil.getFirstDateOfLastYear(endTime);

        //------当前筛选时间的结果
        ElasticAggsPojo thisMonthAggsPojo = otherIncomeAmountElasticAggsPojo(chartResultPojo, ValueTypeEnum.ARRAY_TYPE, typeList);
        ChartResultPojo chartResultPojoCopy = new ChartResultPojo();
        BeanUtil.copyProperties(chartResultPojo, chartResultPojoCopy);
        //------环比结果，把开始结束时间置为环比的开始结束
        chartResultPojoCopy.setStartTime(lastMonthStartTime);
        chartResultPojoCopy.setEndTime(lastMonthEndTime);
        //获取环比同比各自的时间列表
        List<Integer> startTimeList = chartResultPojoCopy.getStartTimeList();
        MomYoyTimeListPojo momYoyTimeListPojo = ChartResultUtil.momYoyTimeListPojo(startTimeList);
        //环比时间处理
        ChartResultUtil.momOrYoyTime(chartResultPojoCopy, true, startTime, endTime);
        chartResultPojoCopy.setStartTimeList(momYoyTimeListPojo.getMomTimeListPojo().getStartTimeList());
        chartResultPojoCopy.setEndTimeList(momYoyTimeListPojo.getMomTimeListPojo().getEndTimeList());
        //------环比结果
        ElasticAggsPojo lastMonthAggsPojo = otherIncomeAmountElasticAggsPojo(chartResultPojoCopy, ValueTypeEnum.ARRAY_TYPE, typeList);
        //------同比结果，把开始结束时间置为同比的开始结束
        chartResultPojoCopy.setStartTime(lastYearStartTime);
        chartResultPojoCopy.setEndTime(lastYearEndTime);
        //同比时间处理
        ChartResultUtil.momOrYoyTime(chartResultPojoCopy, false, startTime, endTime);
        chartResultPojoCopy.setStartTimeList(momYoyTimeListPojo.getYoyTimeListPojo().getStartTimeList());
        chartResultPojoCopy.setEndTimeList(momYoyTimeListPojo.getYoyTimeListPojo().getEndTimeList());
        //------同比结果
        ElasticAggsPojo lastYearAggsPojo = otherIncomeAmountElasticAggsPojo(chartResultPojoCopy, ValueTypeEnum.ARRAY_TYPE, typeList);
        //------处理环比、同比比例
        ElasticAggsPojo resultMom = systemChartHelp.getMomYoyResult(thisMonthAggsPojo, lastMonthAggsPojo);
        ElasticAggsPojo resultYoy = systemChartHelp.getMomYoyResult(thisMonthAggsPojo, lastYearAggsPojo);

        List<StatisticResultInfoDTO> statisticResultInfoDtoList = systemChartHelp.getInfoDtos4MomYoy(chartResultPojo, legendList, unitList, thisMonthAggsPojo, lastMonthAggsPojo, lastYearAggsPojo, resultMom, resultYoy);
        StatisticResultDTO statisticResultDto = new StatisticResultDTO(true, thisMonthAggsPojo.getTotal(), null, statisticResultInfoDtoList);
        return statisticResultDto;
    }

    /**
     * 获取已收款金额统计
     *
     * @param chartResultPojo
     * @param valueTypeEnum
     * @param typeList
     * @return
     * @throws XbbException
     */
    public ElasticAggsPojo otherIncomeAmountElasticAggsPojo(ChartResultPojo chartResultPojo, ValueTypeEnum valueTypeEnum, List<String> typeList) throws XbbException {
        chartResultPojo.setValueTypeEnum(ValueTypeEnum.VALUE_MONEY);
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.otherIncomeQuery4Belong(chartResultPojo, typeList);
        String sumField;
        sumField = OtherIncomeEnum.getEsAttr4Keyword(OtherIncomeEnum.AMOUNT);
        String fieldTime = OtherIncomeEnum.getEsAttr4Keyword(OtherIncomeEnum.INCOME_TIME);
        /*--------得到回款金额--------*/
        // 2019/4/6 不按照多币种计算
        return systemChartHelp.getDouble4Agg(chartResultPojo, valueTypeEnum, IndexTypeEnum.IDX_SAAS_OTHER_INCOME, boolQueryBuilder, fieldTime, sumField);
    }

    /**
     * 对于值的统计
     *
     * @param chartResultPojo 请求系统指标接口需要用到的pojo类（内部存系统指标统计时需要的参数）
     * @return
     * @throws XbbException
     */
    @Override
    public Object getValueTarget(ChartResultPojo chartResultPojo) throws XbbException {
        SystemCodeEnum systemCodeEnum = chartResultPojo.getSystemCodeEnum();
        switch (systemCodeEnum) {
            //其他收入（资金管理）
            case OTHER_INCOME_HOME:
                return otherIncomeHome(chartResultPojo);
            default:
                break;
        }
        return null;
    }

    /**
     * 对其他收入的统计
     *
     * @param chartResultPojo
     * @return
     */
    private String otherIncomeHome(ChartResultPojo chartResultPojo) throws XbbException {
        ElasticAggsPojo elasticAggsPojo = otherIncomeElasticAggsPojo(chartResultPojo, ValueTypeEnum.VALUE_TYPE);
        return ChartResultUtil.formatValue2String(false, ValueTypeEnum.VALUE_MONEY, chartResultPojo.isThousandSwitch(), elasticAggsPojo.getTotal(), NumFormatEnum.getByCode(chartResultPojo.getNumFormat()), chartResultPojo.getNumFormatFlag());
    }

    /**
     * 对其他收入的值统计
     *
     * @param chartResultPojo
     * @param valueTypeEnum
     * @return
     */
    private ElasticAggsPojo otherIncomeElasticAggsPojo(ChartResultPojo chartResultPojo, ValueTypeEnum valueTypeEnum) throws XbbException {
        chartResultPojo.setValueTypeEnum(ValueTypeEnum.VALUE_MONEY);
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.otherIncomeQuery4Belong(chartResultPojo, null);
        String sumField =  OtherIncomeEnum.getEsAttr4Keyword(OtherIncomeEnum.AMOUNT);
        String fieldTime = OtherIncomeEnum.getEsAttr4Keyword(OtherIncomeEnum.INCOME_TIME);
        /*--------得到回款金额--------*/
        // 2019/4/6 不按照多币种计算
        return systemChartHelp.getDouble4Agg(chartResultPojo, valueTypeEnum, IndexTypeEnum.IDX_SAAS_OTHER_INCOME, boolQueryBuilder, fieldTime, sumField);
    }

}
